#!/usr/bin/env bash
# 换源相关：阿里/清华/中科大/华为云/北外/上交；恢复备份
set -Eeuo pipefail

type log_info >/dev/null 2>&1 || { echo "[mirrors] _common.sh 未加载"; exit 1; }

_change_mirror_core() {
  ensure_root
  local key="$1"
  local CODENAME; CODENAME="$(detect_debian_codename)"
  local BACKUP="/etc/apt/sources.list.bak.$(date +%F-%T)"
  local comps="main contrib non-free"
  [[ "$CODENAME" =~ (bookworm|trixie|sid) ]] && comps="$comps non-free-firmware"

  declare -A M=(
    [aliyun]="mirrors.aliyun.com"
    [tuna]="mirrors.tuna.tsinghua.edu.cn"
    [ustc]="mirrors.ustc.edu.cn"
    [huaweicloud]="repo.huaweicloud.com"
    [bfsu]="mirrors.bfsu.edu.cn"
    [sjtu]="mirror.sjtu.edu.cn"
  )
  local host="${M[$key]}"
  [[ -z "$host" ]] && { log_error "不支持的镜像：$key"; return 1; }

  # 备份并写入
  [[ -f /etc/apt/sources.list ]] && cp /etc/apt/sources.list "$BACKUP" || true
  log_info "已备份 sources.list → $BACKUP"

  cat >/etc/apt/sources.list <<EOF
# Debian $CODENAME by $key ($host)
deb https://$host/debian/ $CODENAME $comps
deb https://$host/debian/ $CODENAME-updates $comps
deb https://$host/debian/ $CODENAME-backports $comps
deb https://security.debian.org/debian-security $CODENAME-security $comps
EOF

  log_info "已写入 /etc/apt/sources.list"
  apt-get update -y || true
  log_info "apt 索引已更新"
}

change_mirror_aliyun()      { _change_mirror_core aliyun; }
change_mirror_tuna()        { _change_mirror_core tuna; }
change_mirror_ustc()        { _change_mirror_core ustc; }
change_mirror_huaweicloud() { _change_mirror_core huaweicloud; }
change_mirror_bfsu()        { _change_mirror_core bfsu; }
change_mirror_sjtu()        { _change_mirror_core sjtu; }

restore_sources_backup() {
  ensure_root
  local latest
  latest="$(ls -t /etc/apt/sources.list.bak.* 2>/dev/null | head -n1 || true)"
  [[ -z "$latest" ]] && { log_error "未找到备份文件"; return 1; }
  cp "$latest" /etc/apt/sources.list
  log_info "已恢复：$latest"
  apt-get update -y || true
  log_info "apt 索引已更新"
}
